//
//  HXDPlusViewController.swift
//  weibo
//
//  Created by huxuedong on 15/12/12.
//  Copyright © 2015年 huxuedong. All rights reserved.
//

import UIKit
import SVProgressHUD

class HXDPlusViewController: UIViewController {

    //toolView是否执行动画
    var isToolViewAnimation: Bool = true
    private lazy var toolView: HXDPlusToolView = HXDPlusToolView(frame: CGRectZero)
    
    private lazy var sendButton: UIButton = {
        let button = UIButton()
        button.addTarget(self, action: "send", forControlEvents: .TouchUpInside)
        button.setBackgroundImage(UIImage(named: "common_button_orange"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: UIControlState.Highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Disabled)
        button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Disabled)
        button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        button.setTitle("发送", forState: UIControlState.Normal)
        button.titleLabel?.font = UIFont.systemFontOfSize(15)
        button.size = CGSize(width: 45, height: 30)
        return button
    }()
    
    private lazy var titleView: UILabel = {
        let label = UILabel()
        if let name = HXDUserAccountViewModel.shareInstance.userAccount?.screen_name {
            label.numberOfLines = 0
            //创建富文本对象
            let attributeText = NSMutableAttributedString(string: "发微博\n\(name)")
            let range = (attributeText.string as NSString).rangeOfString(name)
            let attributeTitle = [
                //描边线宽
                NSStrokeWidthAttributeName: 2,
                //描边颜色
                NSStrokeColorAttributeName: UIColor.darkGrayColor()
            ]
            //给指定范围的富文本对象设置样式
            attributeText.addAttributes(attributeTitle, range: NSMakeRange(0, 3))
            let attributeSubTitle = [
                NSFontAttributeName: UIFont.systemFontOfSize(13),
                NSForegroundColorAttributeName: UIColor.grayColor()
            ]
            attributeText.addAttributes(attributeSubTitle, range: range)
            label.attributedText = attributeText
        } else {
            label.text = "发微博"
        }
        label.textAlignment = .Center
        label.sizeToFit()
        return label
    }()
    
    private lazy var textView: HXDPlusTextView = {
        let textView = HXDPlusTextView()
        textView.font = UIFont.systemFontOfSize(15)
        textView.placeholder = "听说下雨天音乐和辣条更配哟~"
        textView.delegate = self
        return textView
    }()
    
    private lazy var plusPictureView: HXDPlusPictureView = {
        let plusPictureView = HXDPlusPictureView()
        //执行添加图片的闭包
        plusPictureView.addImageClosure = {[weak self] in
            self?.selectPicture()
        }
        plusPictureView.backgroundColor = self.textView.backgroundColor
        return plusPictureView
    }()
    
    private lazy var emoticonKeyboard: HXDEmoticonKeyboard = {
        let keyboard = HXDEmoticonKeyboard()
        keyboard.frame = CGRect(x: 0, y: 0, width: kScreenW, height: 216)
        return keyboard
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    private func setupUI() {
        setupNavigation()
        view.addSubview(textView)
        view.addSubview(toolView)
        textView.addSubview(plusPictureView)
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
        }
        toolView.snp_makeConstraints { (make) -> Void in
            make.width.equalTo(self.view)
            make.bottom.equalTo(self.view)
            make.height.equalTo(44)
        }
        plusPictureView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(textView)
            make.width.equalTo(textView).offset(-20)
            make.height.equalTo(textView.snp_width).offset(-20)
            make.top.equalTo(textView).offset(100)
        }
        //执行toolBar按钮的闭包
        toolView.toolViewButtonClickClosure = {(type: HXDPlusToolViewButtonType) -> () in
            switch type {
            case .Picture:
                self.selectPicture()
            case .At:
                printLog("@")
            case .Talk:
                printLog("#")
            case .Emotion:
                self.switchKeyboard()
            case .Add:
                printLog("添加")
            }
        }
        
        //监听键盘的frame，当键盘的frame将要改变时执行对应方法
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "KeyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        //点击表情按钮通知观察者
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "chooseEmoticon:", name: "emoticonButtonClick", object: nil)
        //点击删除表情按钮的通知观察者
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "deleteButtonClick", name: "deleteEmoticon", object: nil)
    }
    
    private func setupNavigation() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: "back")
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        navigationItem.rightBarButtonItem?.enabled = false
        navigationItem.titleView = titleView
    }
    
    @objc private func back() {
        self.view.endEditing(true)
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func KeyboardWillChangeFrame(notification: NSNotification) {
        if !isToolViewAnimation {
            return
        }
        //键盘的结束位置
        let endRect = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        //键盘移动时间
        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber
        toolView.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(self.view).offset(endRect.origin.y - self.view.height)
        }
        UIView.animateWithDuration(duration.doubleValue) { () -> Void in
            self.toolView.layoutIfNeeded()
        }
    }
    
    //选择表情执行的方法
    @objc private func chooseEmoticon(notification: NSNotification) {
        //根据通知，获取到当前点击的表情按钮
        let emoticon = notification.userInfo!["emoticon"] as! HXDEmoticon
        textView.insertEmoticon(emoticon)
    }
    
    @objc private func send() {
        //如果选择图片视图中有图片，则发送图片微博，否则发送文字微博
        if plusPictureView.images.count > 0 {
            upLoadContainImage()
        } else {
            upData()
        }
    }
    
    @objc private func deleteButtonClick(){
        //执行键盘上删除按钮的逻辑
        textView.deleteBackward()
    }
    
    //发送文字微博
    private func upData() {
        HXDNetworkTools.shareTools.upData(HXDUserAccountViewModel.shareInstance.accessToken!, status: textView.emoticonText) { (response, error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("发送失败！")
                return
            } else {
                SVProgressHUD.showSuccessWithStatus("发送成功！")
            }
        }
    }
    
    //发送图片微博
    private func upLoadContainImage() {
        HXDNetworkTools.shareTools.upLoadContainImage(HXDUserAccountViewModel.shareInstance.accessToken!, status: textView.text!, image: plusPictureView.images.first!) { (response, error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("发送失败！")
                return
            } else {
                SVProgressHUD.showSuccessWithStatus("发送成功！")
            }
        }
    }
    
    private func selectPicture() {
        //创建图片选择控制器，默认UIImagePickerControllerSourceType = PhotoLibrary
        let pickerController = UIImagePickerController()
        pickerController.delegate = self
        presentViewController(pickerController, animated: true, completion: nil)
    }
    
    //选择弹出的键盘(系统键盘或者表情键盘)
    private func switchKeyboard() {
        isToolViewAnimation = false
        textView.resignFirstResponder()
        //当inputView == nil时，为系统默认键盘
        textView.inputView = (textView.inputView == nil) ? emoticonKeyboard : nil
        toolView.isEmoticonKeyBoard = (textView.inputView != nil)
        isToolViewAnimation = true
        textView.becomeFirstResponder()
    }

}

extension HXDPlusViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    //选择图片完成时调用
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        //将选择的图片缩放后进行添加
        plusPictureView.addImage(image.scaleToWidth(600))
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    //点击图片选择控制器的取消按钮时调用
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
}

//遵守协议，实现代理方法
extension HXDPlusViewController: UITextViewDelegate {
    
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    //当滚动时回收键盘
    func scrollViewDidScroll(scrollView: UIScrollView) {
        self.view.endEditing(true)
    }
    
}
